package lbframework.bean.comboBox;

import java.awt.Color;
import java.awt.Component;
import java.awt.KeyboardFocusManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.KeyStroke;
import javax.swing.ListCellRenderer;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.plaf.ColorUIResource;
import javax.swing.plaf.basic.BasicComboBoxRenderer;
import lbframework.classe.Conexao;
import lbframework.classe.Util;
import lbframework.remote.ItemComboVO;

public class LBComboBox extends javax.swing.JComboBox {

    private String campoId = "id";
    private String campoDescricao = "descricao";
    private String tabela = "";
    private String filtro = "";
    private String campoOrdenacao = "";
    private boolean checkBox = false;
    private boolean enabled = true;
    private boolean obrigatorio = false;

    public LBComboBox() {
        initComponents();

        HashSet kTab = new HashSet(1);
        kTab.add(KeyStroke.getKeyStroke("TAB"));
        kTab.add(KeyStroke.getKeyStroke("ENTER"));

        setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, kTab);

        UIManager.put("ComboBox.disabledForeground", new ColorUIResource(Color.BLACK));
    }

    public void setDescricao(String i_descricao) {
        boolean achou = false;

        for (int i = 0; i < this.getItemCount(); i++) {
            if (((ItemComboVO) this.getItemAt(i)).descricao.equals(i_descricao)) {
                setSelectedIndex(i);
                achou = true;

                break;
            }
        }

        if (!achou) {
            setSelectedIndex(-1);
        }
    }

    public void setId(int i_id) {
        boolean achou = false;

        for (int i = 0; i < this.getItemCount(); i++) {
            if (((ItemComboVO) this.getItemAt(i)).id == i_id) {
                if (isCheckBox()) {
                    setSelecionado(i, true);
                } else {
                    setSelectedIndex(i);
                    achou = true;
                }

                break;
            }
        }

        if (!achou) {
            setSelectedIndex(-1);
        }
    }

    public int getId() {
        if (this.getSelectedIndex() >= 0) {
            return ((ItemComboVO) this.getSelectedItem()).id;
        } else {
            return -1;
        }
    }

    public int getId(int i_index) {
        return ((ItemComboVO) this.getItemAt(i_index)).id;
    }

    public String getDescricao() {
        if (this.getSelectedIndex() >= 0) {
            return ((ItemComboVO) this.getSelectedItem()).descricao;
        } else {
            return "";
        }
    }

    public boolean isSelecionado(int i_index) {
        return ((ItemComboVO) this.getItemAt(i_index)).selecionado;
    }

    public boolean isSelecionado() {
        for (int i = 0; i < getItemCount(); i++) {
            if (isSelecionado(i)) {
                return true;
            }
        }

        return false;
    }

    public void setSelecionado(int i_index, boolean i_selecionado) {
        ((ItemComboVO) this.getItemAt(i_index)).selecionado = i_selecionado;
    }

    public void setSelecionado(boolean i_selecionado) {
        for (int i = 0; i < getItemCount(); i++) {
            setSelecionado(i, i_selecionado);
        }
    }

    public void carregar() throws Exception {
        Statement stm = null;
        ResultSet rst = null;
        StringBuilder sql = null;

        this.removeAllItems();

        stm = Conexao.createStatement();

        sql = new StringBuilder();
        sql.append("SELECT " + campoId + "," + campoDescricao + " FROM " + tabela);

        if (!filtro.equals("")) {
            sql.append(" " + filtro);
        }
        
        if (!campoOrdenacao.equals("")) {
            sql.append(" ORDER BY " + campoOrdenacao);
        } else {
            sql.append(" ORDER BY " + campoDescricao);
        }

        rst = stm.executeQuery(sql.toString());

        while (rst.next()) {
            ItemComboVO oItemCombo = new ItemComboVO();
            oItemCombo.descricao = rst.getString(campoDescricao);
            oItemCombo.id = rst.getInt(campoId);

            this.addItem(oItemCombo);
        }

        stm.close();
    }

    public void setCampoId(String campoId) {
        this.campoId = campoId;
    }

    public String getCampoId() {
        return campoId;
    }

    public void setCampoDescricao(String campoDescricao) {
        this.campoDescricao = campoDescricao;
    }

    public String getCampoDescricao() {
        return campoDescricao;
    }

    public void setTabela(String tabela) {
        this.tabela = tabela;
    }

    public String getTabela() {
        return tabela;
    }

    public void setFiltro(String filtro) {
        this.filtro = filtro;
    }

    public String getFiltro() {
        return filtro;
    }

    public boolean isCheckBox() {
        return checkBox;
    }

    public String getCampoOrdenacao() {
        return campoOrdenacao;
    }

    public void setCampoOrdenacao(String i_campo, String i_ordenacao) {
        this.campoOrdenacao = i_campo + " " + i_ordenacao;
    }

    public void setCheckBox(boolean value) {
        checkBox = value;

        if (value) {
            this.setRenderer(new MyListCellRenderer());
        } else {
            this.setRenderer(new BasicComboBoxRenderer());
        }
    }

    /**
     *
     * @param anObject = new ItemComboVO(id,descricao)
     */
    @Override
    public void addItem(Object anObject) {
        super.addItem(anObject);
    }

    @Override
    public void setEnabled(boolean b) {
        this.enabled = b;

        if (b || !b && !isCheckBox()) {
            super.setEnabled(b);
        }

        setObrigatorio(obrigatorio);
    }

    public boolean isObrigatorio() {
        return obrigatorio;
    }

    public void setObrigatorio(boolean obrigatorio) {
        this.obrigatorio = obrigatorio;

        if (this.isEnabled()) {
            if (obrigatorio) {
                this.setBackground(Util.COR_OBRIGATORIO);
            } else {
                this.setBackground(UIManager.getColor("ComboBox.background"));
            }
        } else {
            this.setBackground(UIManager.getColor("ComboBox.disabledBackground"));
        }
    }

    public String getSelecionados() throws Exception {
        List selecionados = new ArrayList();

        for (int i = 0; i < getItemCount(); i++) {
            if (isSelecionado(i)) {
                selecionados.add(getId(i));
            }
        }

        return selecionados.toString().replace("[", "").replace("]", "");
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        setPreferredSize(new java.awt.Dimension(29, 20));
        addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                formActionPerformed(evt);
            }
        });
    }// </editor-fold>//GEN-END:initComponents

    private void formActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_formActionPerformed
        if (isCheckBox()) {
            JComboBox comboBox = (JComboBox) evt.getSource();

            if (comboBox.getSelectedItem() != null) {
                ItemComboVO oItemCombo = (ItemComboVO) comboBox.getSelectedItem();

                MyListCellRenderer oRenderer = (MyListCellRenderer) comboBox.getRenderer();

                if (this.enabled) {
                    oRenderer.checkBox.setSelected((oItemCombo.selecionado = !oItemCombo.selecionado));
                }

                setId(-1);

                Runnable doEvent = new Runnable() {

                    public void run() {
                        showPopup();
                    }
                };

                SwingUtilities.invokeLater(doEvent);
            }
        }
    }//GEN-LAST:event_formActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables
    private String getDescricaoCheckBox() {
        if (isCheckBox()) {
            String descricao = "";
            int cont = 0;

            for (int i = 0; i < getItemCount(); i++) {
                if (isSelecionado(i)) {
                    cont++;

                    if (cont == 1) {
                        descricao = " " + ((ItemComboVO) getItemAt(i)).descricao;
                    } else {
                        descricao = " " + cont + " ITENS";
                    }
                }
            }

            return descricao;

        } else {
            return "";
        }
    }

    class MyListCellRenderer implements ListCellRenderer {

        JCheckBox checkBox;

        public MyListCellRenderer() {
            checkBox = new JCheckBox();
        }

        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            if (value == null || (index == -1 && value.equals(" "))) {
                JLabel lblCampo = new JLabel();

                lblCampo.setOpaque(true);
                lblCampo.setText(getDescricaoCheckBox());

                return lblCampo;
            }

            ItemComboVO oItemCombo = (ItemComboVO) value;

            checkBox.setText(oItemCombo.descricao);
            checkBox.setSelected(oItemCombo.selecionado);

            if (isSelected) {
                checkBox.setBackground(UIManager.getColor("ComboBox.selectionBackground"));
            } else {
                if (obrigatorio) {
                    checkBox.setBackground(Util.COR_OBRIGATORIO);
                } else {
                    if (isEnabled()) {
                        checkBox.setBackground(UIManager.getColor("ComboBox.background"));
                    } else {
                        checkBox.setBackground(UIManager.getColor("ComboBox.disabledBackground"));
                    }
                }
            }

            if (isSelected) {
                checkBox.setForeground(UIManager.getColor("ComboBox.selectionForeground"));
            } else {
                checkBox.setForeground(UIManager.getColor("ComboBox.foreground"));
            }

            checkBox.setEnabled(enabled);

            return checkBox;
        }
    }
}
